import NMEA, serial, math, glob
import utils



# Minimum distance that the walker must be from an recording to
# trigger its playback (in lat and long degrees).
triggerRadius = 0.0003

# A dictionary of GPS values that relates to the filenames.
gpsLibrary = {}

# A list of filenames that have already been played. Used to make sure
# that the same file is not played twice.
previouslyPlayedFiles = []



def getPreviousRecordings():
  """
  Builds a dictionary of the previous recordings positions by
  extracting their GPS lat and long values from their filenames.
  """

  global gpsLibrary

  filenames = glob.glob(utils.mediaDirectory + '/*.wav')

  for index, item in enumerate(filenames):
    # The lat and long values are at the end of the filename,
    # preceded by an underscore. Slice the characters of each filename
    # at that point, and remove the .wav file extension.

    # Remove the directory name from the path.
    filename = item[len(utils.mediaDirectory) + 1:]
    sliceIndex = item.rfind('_')
    if sliceIndex != -1:
      item = item[sliceIndex + 1:-4]
      # Extract the individual lat and lon values.
      lonSliceIndex = item.find('lon')
      lat = item[3:lonSliceIndex]
      lon = item[lonSliceIndex+3:]

      # Add them to the main GPS values dictionary.
      # Dictionary structure: { filename: [lat, long] }
      latLongValues = []
      latLongValues.append(lat)
      latLongValues.append(lon)
      gpsLibrary[filename] = latLongValues

  print "Library loaded: " + str(len(gpsLibrary)) + " files found."
  print ""



def monitorLocation():
  """
  Read the current GPS location, and playback file if necessary.
  """

  global triggerRadius

  pos = utils.getLocation()
  #print 'Current location: lat:' + str(pos[0]) + ' lon:' + str(pos[1])
  
  # Loop through the dictionary of previous recordings and compare
  # the current location to their tagged locations. If the distance
  # is less than the tigger radius, the file may be played.
  
  for filename, location in gpsLibrary.iteritems():
    # Measure the distance between the current and recorded points.
    distance = getDistance(pos[0], pos[1], float(location[0]), float(location[1]))

    if distance < triggerRadius:
      # Check that it has not already been played.
      if filename not in previouslyPlayedFiles:
        #print "Recording found. Distance: " + str(distance)
        # Add the file to the list of previously played files.
        previouslyPlayedFiles.append(filename)
        #print "Playback file " + filename
        utils.play(filename)



def getDistance(x1, y1, x2, y2):
  """
  Returns distance between two points using the pythagorean theorem.
  """
  dx = x2 - x1
  dy = y2 - y1
  return math.sqrt(dx**2 + dy**2)



# Build the dictionary of previous recordings.
getPreviousRecordings()

# Monitor current location.
while 1:
  monitorLocation()
